package com.zjq.designpatterns.behaviors.interpreter.code;/*
 * 版权信息: 北京千⾥马网信科技有限公司</br>
 * Copyright ©2008-2018. All rights reserved. 京ICP备16007318号
 */

import java.util.Stack;

/**
 * @author jessie
 * @version 1.0
 * @date 2021/1/27
 */
public class GeelyExpressionParser {
    private Stack<Interpreter> stack = new Stack<>();

    public int parse(String str){
        String[] strItemArray = str.split(" ");
        for(String symbol: strItemArray){
            if(!OperatorUtil.isOperator(symbol)){
                Interpreter numberExpression = new NumberInterpreter(symbol);
                stack.push(numberExpression);
                System.out.println(String.format("入栈: %d", numberExpression.interpret()));
            }else{
                //是运算符号可以计算
                Interpreter firstExpression = stack.pop();
                Interpreter secondExpression = stack.pop();
                System.out.println(String.format("出栈: %d 和 %d", firstExpression.interpret(), secondExpression.interpret()));
                Interpreter operator = OperatorUtil.getExpressionObject(firstExpression, secondExpression, symbol);
                System.out.println(String.format("应用运算符: %s", operator));
                int result = operator.interpret();
                NumberInterpreter resultExpression = new NumberInterpreter(result);
                stack.push(resultExpression);
                System.out.println(String.format("阶段结果入栈：%d", result));
            }
        }
        int result = stack.pop().interpret();
        return result;
    }
}
